<template>
  <div class="upload-container">
    <el-button
      icon="el-icon-upload"
      size="mini"
      :style="{background:color,borderColor:color}"
      type="primary"
      @click="dialogVisible=true"
    />
    <el-dialog :visible.sync="dialogVisible" width="80%" append-to-body title="通用文件上传" :close-on-click-modal="false">
      <el-tabs v-model="activeName">
        <el-tab-pane label="上传文件" name="first">
          <el-row>
            <el-col :xs="24" :sm="24" :md="12" :lg="12" :xl="12">
              <el-row>
                <el-alert type="warning">请先选择目录</el-alert>
                <crmdirectoryselector :id="selected_directory" :name="selected_directory__name" @change="handleDirectoryChange" />
              </el-row>
              <el-row>
                <el-divider content-position="left">选项参数</el-divider>
                <el-input v-model="combin_search_keyword" size="mini" placeholder="tag/关键词" style="width: 120px" />
                <el-select v-model="acl_type" placeholder="访问权限" size="mini" filterable>
                  <el-option label="7天临时链接" value="7" />
                  <el-option label="3天临时链接" value="3" />
                  <el-option label="公开共享" value="public_read" />
                </el-select>
                <el-switch
                  v-model="addwatermark"
                  active-text="添加水印"
                  inactive-text="不添加"
                  title="插入水印"
                  active-color="#13ce66"
                  inactive-color="#ff4949"
                />
                <el-switch
                  v-model="removebg"
                  active-text="自动抠图"
                  inactive-text="不处理"
                  title="抠图"
                  active-color="#13ce66"
                  inactive-color="#ff4949"
                />
                <el-divider content-position="left">选择文件</el-divider>
                <el-upload
                  ref="upload"
                  :headers="headers"
                  :action="upload_url"
                  :multiple="true"
                  drag
                  :auto-upload="false"
                  :file-list="fileList"
                  :show-file-list="true"
                  :before-upload="beforeUpload"
                  :data="{ directory_id:selected_directory||-1,acl_type: this.acl_type, removebg:this.removebg, addwatermark: this.addwatermark, search_term: combin_search_keyword,
                           project_id: this.$store.getters.projectId}"
                  :on-remove="handleRemove"
                  :on-success="handleSuccess"
                  multiple
                >
                  <i class="el-icon-upload" />
                  <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
                  <div slot="tip" class="el-upload__tip">过大文件请使用网盘</div>
                </el-upload>
                <el-button style="margin-left: 10px;" size="small" type="success" @click="submitUpload">上传到服务器</el-button>
                <el-alert
                  v-if="selected_directory__name !== ''"
                  :title="'文件会上传到目录' + selected_directory__name"
                  type="info"
                  :closable="false"
                />
                <el-alert
                  v-else
                  title="先选择目录,然后上传图片"
                  type="error"
                  :closable="false"
                />
              </el-row>

            </el-col>
            <el-col :xs="24" :sm="24" :md="12" :lg="12" :xl="12">
              <div class="paste-area" @paste="handlePaste">
                <span>点击这里并粘贴图片</span>
                <div v-if="imageUrl">
                  <img style="width: 100px; height: 100px" :src="imageUrl" alt="粘贴的图片">
                </div>
                <button v-if="imageUrl" size="mini" @click="imageUrl=null">清空图片</button>

                <el-button v-if="imageUrl" @click="handleCreateFile">保存</el-button>
              </div>
              <div style="margin-top: 10px">
                <span>直接通过URL插入图片</span>
                <el-image
                  v-for="(remote_url,index) in remoteUrls"
                  v-if="remoteUrls.length !== 0"
                  :key="index"
                  :src="remote_url"
                  :preview-src-list="remoteUrls"
                  style="width: 100px; height: auto"
                />
                <el-input v-model="remote_url" type="textarea" placeholder="请输入内容" />
                <el-button type="success" @click="handleInsertFile({url: remote_url})">不上传直接插入</el-button>
              </div>

              <ul v-if="success_data.length !== 0">
                <li v-for="(item,index) in success_data" :key="index">
                  <el-image v-if="item.content_type.indexOf('image') !== -1" style="max-width: 200px;" :src="item.url" :preview-src-list="[item.url]" />
                  <el-link v-else type="success" :href="item.url" target="_blank">{{ item.filename }}</el-link>
                  <el-button type="primary" icon="el-icon-circle-plus" @click="handleInsertFile(item)">插入</el-button>
                </li>
              </ul>
            </el-col>
          </el-row>
        </el-tab-pane>
        <el-tab-pane label="浏览附件" name="second">
          <el-row>
            <el-col :xs="24" :sm="6" :md="6" :lg="6" :xl="6">
              <crmdirectoryselector :id="selected_directory" :name="selected_directory__name" @change="handleChangeSearchDirectory" />
              <el-button icon="el-icon-refresh" @click="handleGetFiles" />
            </el-col>
            <el-col :xs="24" :sm="18" :md="18" :lg="18" :xl="18">
              <el-table v-loading="listLoading" :data="files" :show-header="false" fit highlight-current-row style="width: 100%">
                <el-table-column
                  type="selection"
                  width="55"
                />
                <el-table-column align="left" width="200" prop="url" label="缩略图">
                  <template v-if="scope.row.content_type.indexOf('image') !== -1" slot-scope="scope">
                    <img :src="scope.row.url" style="height: 100px; width: 100px">
                  </template>
                </el-table-column>
                <el-table-column align="left" label="存放" prop="save_in" />
                <el-table-column align="left" label="filename" prop="filename">
                  <template slot-scope="scope">
                    <a :href="scope.row.url" target="_blank">{{ scope.row.filename }}</a>
                  </template>
                </el-table-column>
                <el-table-column align="center" label="操作" width="250">
                  <template slot-scope="scope">
                    <el-button size="mini" type="primary" icon="el-icon-set-up" @click="handleTranslate(scope.row)">翻 译</el-button>
                    <el-button size="mini" type="danger" icon="el-icon-delete" :loading="operateloading" @click="handleDeleteFile(scope.row)">删 除</el-button>
                    <el-button type="primary" size="mini" icon="el-icon-circle-plus" @click="handleInsertFile(scope.row)">插入</el-button>
                  </template>
                </el-table-column>

              </el-table>
              <el-pagination
                v-if="files.length"
                background
                class="mt-pagination"
                :current-page="page"
                :page-sizes="[10,20,50,100]"
                :page-size="pagesize"
                layout="total, sizes, prev, pager, next, jumper"
                :total="total"
              />
            </el-col>
          </el-row>
        </el-tab-pane>
      </el-tabs>
      <span slot="footer">
        <el-button @click="dialogVisible = false">关 闭</el-button>
        <el-button size="mini" type="primary" @click="handleInsertFile(item)">插 入</el-button>
      </span>
    </el-dialog>
    <el-dialog :visible.sync="translateBoxVisible" append-to-body title="翻译文件">
      <el-form>
        <el-form-item label="源语言">
          <el-select v-model="current_item.source_language" placeholder="请选择">
            <el-optioin v-for="item in languages" :key="item.code" :label="item.label" :value="item.code" />
          </el-select>
        </el-form-item>
        <el-form-item label="目标语言">
          <el-select v-model="current_item.target_language" placeholder="请选择">
            <el-optioin v-for="item in languages" :key="item.code" :label="item.label" :value="item.code" />
          </el-select>
        </el-form-item>
        <el-form-item label="翻译结果">
          <el-input v-model="current_item.translated_content" type="textarea" />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleInsert">插入</el-button>
        </el-form-item>
      </el-form>
      <span slot="footer">
        <el-button @click="translateBoxVisible = false">关 闭</el-button>
        <el-button size="mini" type="primary" @click="translateFile">翻 译</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { getToken } from '@/utils/auth'
import Crmdirectoryselector from './crmdirectoryselector'
import { Get as GetFile, Delete, SaveBase64Image } from '@/api/crm/crmfile'
import qs from 'qs'
import { languages } from '../../../api/crm/crmcommon'

export default {
  name: 'Crmcommonfilesmanager',
  components: { Crmdirectoryselector },
  props: {
    color: {
      type: String,
      default: '#1890ff'
    },
    urllist: {
      type: Array,
      default: () => []
    }
  },
  data() {
    return {
      operateloading: false,
      listLoading: false,
      activeName: 'first',
      dialogVisible: false,
      listObj: {},
      fileList: [],
      upload_url: '',
      success_data: [],
      remote_url: '',
      translateBoxVisible: false,
      current_item: {
        id: '',
        url: '',
        filename: '',
        source_language: 'en',
        target_language: 'zh'
      },
      languages: languages,
      boolUploadSucceed: false,
      combin_search_keyword: '',
      selected_directory: null,
      acl_type: 'public_read',
      addwatermark: true,
      removebg: true,
      search_directory_id: '',
      selected_directory__name: null,
      temp: {
        file_data: '',
        content_type: 'image/base64'
      },
      imageUrl: '',
      files: [],
      order_by: 'used_time',
      order_desc: 1,
      // pagination
      pagesize: 20,
      page: 1,
      total: 0
    }
  },
  computed: {
    remoteUrls() {
      return this.remote_url.split('\n').filter(item => item.length > 0)
    },
    headers() {
      return {
        'Authorization': getToken()
      }
    }
  },
  mounted() {
    this.boolUploadSucceed = false
    this.upload_url = process.env.VUE_APP_BASE_API + '/crm/api/crmfile/'
  },
  methods: {
    translateFile() {
      console.log(this.current_item)
    },
    handleDirectoryChange(data) {
      this.selected_directory = data.id
      this.selected_directory__name = data.name
    },
    handleChangeSearchDirectory(data) {
      if (!data) return
      let directoryId = ''
      if (data.id) {
        if (Array.isArray(data.id)) {
          directoryId = data.id.length > 0
            ? data.id[data.id.length - 1]
            : ''
        } else {
          directoryId = data.id.toString()
        }
      }

      this.search_directory_id = directoryId
      this.handleGetFiles()
    },
    handleDeleteFile(item) {
      this.operateloading = true
      Delete(item.id).then((response) => {
        this.notify('删除成功')
        this.handleGetFiles()
        this.operateloading = false
      })
    },
    handleCreateFile() {
      if (this.selected_directory === null) {
        alert('请选择目录')
        return
      }
      this.temp.directory_id = this.selected_directory
      this.temp.search_term = this.combin_search_keyword
      this.temp.acl_type = this.acl_type
      this.temp.addwatermark = this.addwatermark
      this.temp.removebg = this.removebg
      SaveBase64Image(this.temp).then(response => {
        this.success_data.push(response.data)
      })
    },
    readFileAsBase64(file) {
      const reader = new FileReader()
      reader.onload = (e) => {
        this.imageUrl = e.target.result
        this.temp.file_data = this.imageUrl
      }
      reader.readAsDataURL(file)
    },
    handlePaste(event) {
      const items = (event.clipboardData || event.originalEvent.clipboardData).items
      for (const item of items) {
        if (item.type.indexOf('image') === 0) {
          const file = item.getAsFile()
          this.readFileAsBase64(file)
        }
      }
    },
    handleGetFiles() {
      this.listLoading = true
      GetFile(null, qs.stringify({
        kw: this.kwInput,
        directory_id: this.search_directory_id,
        pagesize: this.pagesize,
        page: this.page,
        order_by: this.order_by,
        order_desc: this.order_desc
      }))
        .then(response => {
          this.files = response.data.data
          this.listLoading = false
          this.total = response.data.total
        }).catch(err => {
          console.log(err)
          this.listLoading = false
        })
    },
    deleteRow(index) {
      console.log('delete ', index)
      const arr = []
      for (let i = 0; i < this.combin_form.urls.length; i++) {
        if (index !== i) {
          arr.push(this.combin_form.urls[i])
        }
      }
      this.combin_form.urls = arr
      // this.combin_form.urls = this.combin_form.urls.slice(index, 1)
    },
    handleChoose(v) {
      const url = v.toElement.currentSrc
      if (url) {
        let is_in = false
        for (let i = 0; i < this.combin_form.urls.length; i++) {
          if (this.combin_form.urls[i].url === url) {
            is_in = true
          }
        }
        if (!is_in) {
          this.combin_form.urls.push({ url: url })
        }
        console.log('add', v.toElement.currentSrc)
      }
    },
    handleAdd(v) {
      this.images = this.combin_form.search_urls.trim().split('\n').filter(item => item.length > 0)
    },
    handleInsert() {
      // window.open(this.new_image_url, '_blank')
      const arr = []
      arr.push({ 'url': this.new_image_url, width: this.combin_form.width, height: this.combin_form.height })
      this.$emit('successCBK', arr)
      this.dialogVisible = false
    },
    checkAllSuccess() {
      return Object.keys(this.listObj).every(item => this.listObj[item].hasSuccess)
    },
    handleSubmit() {
      if (this.selected_directory === null) {
        alert('请选择目录')
        return
      }
      const arr = Object.keys(this.listObj).map(v => this.listObj[v])
      if (!this.checkAllSuccess()) {
        this.$message('请等待所有文件上传成功 或 出现了网络问题，请刷新页面重新上传！')
        return
      }
      this.listObj = {}
      this.fileList = []
      this.success_data = []
      this.boolUploadSucceed = false
      this.$emit('successCBK', arr)
    },
    handleTranslate(item) {
      this.translateBoxVisible = true
      this.current_item = item
    },
    handleInsertFile(item) {
      // 按换行符分割
      const urls = item.url.split('\n')
      urls.forEach(url => {
        this.urllist.push(url)
        this.$emit('insert', { url: url })
      })
      // this.urllist.push(item.url)
      console.log(this.urllist)
      this.$emit('insert', item)
      this.dialogVisible = false
    },
    handleSuccess(response, file) {
      if (response.success) {
        this.$notify({
          title: '成功',
          message: `文件${file.name}上传成功`,
          type: 'success',
          duration: 1000
        })
        const uid = file.uid
        const objKeyArr = Object.keys(this.listObj)
        for (let i = 0, len = objKeyArr.length; i < len; i++) {
          if (this.listObj[objKeyArr[i]].uid === uid) {
            this.listObj[objKeyArr[i]].url = response.data.url
            this.success_data.push(response.data)
            this.listObj[objKeyArr[i]].hasSuccess = true
            return
          }
        }
      } else {
        this.$notify({
          title: '失败',
          message: `文件${file.name}上传失败, ${response.msg}`,
          type: 'error',
          duration: 3000
        })
      }
    },
    submitUpload() {
      this.$refs.upload.submit()
    },
    handleRemove(file) {
      const uid = file.uid
      const objKeyArr = Object.keys(this.listObj)
      for (let i = 0, len = objKeyArr.length; i < len; i++) {
        if (this.listObj[objKeyArr[i]].uid === uid) {
          delete this.listObj[objKeyArr[i]]
          return
        }
      }
    },
    beforeUpload(file) {
      const _self = this
      const fileName = file.uid
      this.listObj[fileName] = {}
      return new Promise((resolve, reject) => {
        _self.listObj[fileName] = { hasSuccess: false, uid: file.uid }
        resolve(true)
      })
    }
  }
}
</script>

<style rel="stylesheet/scss" lang="scss" scoped>
  .paste-area {
    border: 2px dashed #ccc;
    padding: 20px;
    text-align: center;
  }
  .editor-slide-upload {
    margin-bottom: 20px;
    :deep(.el-upload--picture-card) {
      width: 100%;
    }
  }
</style>
